package com.kedll.library.crop;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.widget.Toast;

import com.kedll.library.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * 文件工具类
 */
public class FileUtil {
    private static final String TAG = "FileUtil";
    public static final String CHAT_IMAGES_ROOT_PATH = getExternalStorePath() + "/images/";
    public static final String CHAT_VIDEO_ROOT_PATH = getExternalStorePath() + "/videos/";

    /**
     * 照片转byte二进制
     * @param imagepath 需要转byte的照片路径
     * @return 已经转成的byte
     * @throws Exception
     */
    public static byte[] readStream(String imagepath) throws Exception {
        FileInputStream fs = new FileInputStream(imagepath);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while (-1 != (len = fs.read(buffer))) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        fs.close();
        return outStream.toByteArray();
    }


    /**
     * 根据url获取文件名
     *
     * @param url
     * @return
     */
    public static String getFileName(String url) {
        Log.e("头像本地路径---",url);
        int index = url.lastIndexOf("/") + 1;
        return url.substring(index);
    }

    /**
     * 获取文件大小
     *
     * @param file
     * @return
     */
    public static long getFileSize(File file) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            return fis.available();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            if (null != fis) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        }
    }

    /**
     * 获取单个文件的MD5值！
     *
     * @param file
     * @return
     */

    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

    /**
     * 获取原图片存储路径
     *
     * @param ctx       上下文
     * @param imageName 图片名字
     * @return 原图片的存储路径
     */
    public static String getPhotoPath(Context ctx, String imageName) {

        if (!isExistExternalStore()) {
            Toast.makeText(ctx, "存储卡已拔出", Toast.LENGTH_SHORT).show();
            return null;
        }

        // 照片全路径  
        String fileName = "";
        // 文件夹路径  
//        String pathUrl = CHAT_IMAGES_ROOT_PATH;
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), ctx.getPackageName());
        if (!file.exists()) {
            if (!file.mkdirs()) {
                return null;
            }
        }
        if (imageName == null) {
            return null;
        }
        fileName = file.getPath().concat(File.separator).concat(imageName);
        return fileName;
    }

    /**
     * 图片存储路劲
     *
     * @param ctx
     * @return
     */
    public static String getPhotoDirectory(Context ctx) {
        if (!isExistExternalStore()) {
            Toast.makeText(ctx, "存储卡已拔出", Toast.LENGTH_SHORT).show();
            return null;
        }

        // 文件夹路径
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), ctx.getPackageName());
        if (!file.exists()) {
            if (!file.mkdirs()) {
                return null;
            }
        }
        return file.getPath();
    }

    /**
     * 获取原视频存储路径
     *
     * @param ctx       上下文
     * @param videoName 图片名字
     * @return 原视频的存储路径
     */
    public static String getVideoPath(Context ctx, String videoName) {

        if (!isExistExternalStore()) {
            Toast.makeText(ctx, "存储卡已拔出", Toast.LENGTH_SHORT).show();
            return null;
        }

        // 照片全路径
        String fileName = "";
        // 文件夹路径
//        String pathUrl = CHAT_IMAGES_ROOT_PATH;
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), ctx.getPackageName());
        if (!file.exists()) {
            if (!file.mkdirs()) {
                return null;
            }
        }
        if (videoName == null) {
            return null;
        }
        fileName = file.getPath().concat(File.separator).concat(videoName);
        return fileName;
    }

    public static String getVideoDirectory(Context ctx) {

        if (!isExistExternalStore()) {
            Toast.makeText(ctx, "存储卡已拔出", Toast.LENGTH_SHORT).show();
            return null;
        }

        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), ctx.getPackageName());
        if (!file.exists()) {
            if (!file.mkdirs()) {
                return null;
            }
        }
        return file.getPath().concat(File.separator);
    }


    public static String getExternalStorePath() {
        if (isExistExternalStore()) {
//            return BaseApplication.getInstance().getExternalCacheDir().getAbsolutePath();
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return null;
    }

    /**
     * 是否有外存卡
     *
     * @return true = 存在SD卡, false = 不存在SD卡
     */
    public static boolean isExistExternalStore() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /**
     * 根据Uri获取图片绝对路径，解决Android4.4以上版本Uri转换
     *
     * @param context
     * @param imageUri
     * @author yaoxing
     * @date 2014-10-12
     */
    @TargetApi(19)
    public static String getImageAbsolutePath(Activity context, Uri imageUri) {
        if (context == null || imageUri == null) {
            return null;
        }
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri)) {
                return imageUri.getLastPathSegment();
            }
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

}
